<template>
  <div class="form-item col-1">

    <div>
      <div style="margin-top: 15px" :class="{'sortable-body': true, 'in-drag': inDrag,'out-drag': !inDrag}">

        <!-- 拖拽容器 -->
        <draggable
            tag="ul"
            :list="tab_list"
            v-bind="dragOptions"
            @start="inDrag = true">

          <!-- 动画 -->
          <transition-group type="transition" :name="!inDrag ? 'flip-list' : null">

            <!-- item -->
            <li
                v-for="(item, index) in tab_list"
                :key="item.id"
                :class="{'in-hover': inHover == item.id}"
                @mousemove="inHover = item.id"
                @mouseleave="inHover = ''">

              <div class="top" style="display: flex;">
                <div style="width: 295px">
                  <a-input
                      v-model.trim="item.text" :maxLength="6" addon-after="最多6个字"
                      placeholder="请输入一级选项卡名称">
                  </a-input>
                </div>
              </div>

              <div class="bottom">
                <div class="left">
                  <div class="show-img" v-if="item.image" @click="openUpload(item.id)">
                    <img :src="item.image">
                    <a-icon class="icon-close11" type="close-circle"  @click.stop="deleteImg(item)" title="点击清除图片"/>
                  </div>
                  <div class="choose-img" v-else @click="openUpload(item.id)">
                    <i class="iconfont icon-jiahao"></i>
                    <span>点击上传</span>
                  </div>
                </div>

                <div class="right" :style="{marginLeft: '10px'}">
                  <div class="slide-bar-wrapper" style="margin-top: 10px">
                    如果选择上传图片，该一级选项卡只显示图片，
                    建议尺寸300*300
                  </div>
                </div>
              </div>

              <a-button type="primary" style="width: 290px;margin-top: 15px;"  @click="setCurrentSecondList(item)">
                设置二级选项卡
              </a-button>

              <div class="id-name">
                ID： {{item.id}}
              </div>
              <div class="buttons">
                <span class="ignore-elements" @click.stop="handle_component_delete(item.id)">
                   <i class="iconfont icon-ht_operation_delete"/>
                 </span>
              </div>
              <!-- <image-upload :ref="`imageUpload`+item.id"
                            :value.sync="item.image"
                            :config="config"
                            :rootConfig="rootConfig"
                            @confirm="sureImg(item,$event)">
              </image-upload> -->
              <images-upload :ref="`imageUpload`+item.id" :type=1 selNum='one' @sure='(name,uploadShow,fileList) => {sureImg(item,name,uploadShow,fileList)}'>

              </images-upload>							
            </li>
          </transition-group>

        </draggable>

        <!-- 删除所有组件 -->
        <div style="text-align: left;margin-top: 10px">
          <a-button type="primary" style="width: 310px" @click="toAdd">
            添加更多
          </a-button>
        </div>
      </div>
    </div>

    <a-modal v-model="showSecondTab" :maskClosable="false" title="设置二级选项卡" @cancel="handleSecondOk" @ok="handleSecondOk">
      <div>
        <div style="margin-bottom: 10px">
          <div class="title-box">
            <span style="flex: 0 0 100px">二级选项卡：</span>
          </div>
          <draggable
              tag="div" class="tab-box"
              :list="current_second_list"
              v-bind="dragOptions">

            <div class="tab-item" :class="[tab_active == item.id?'active':'']" v-for="item in current_second_list" :key="item.id" @click="chooseSecondIt(item)">
              <span>选项卡名称：</span>
              <a-input v-model.trim="item.title" style="width: 80px;" :maxLength="4" placeholder="名称">
              </a-input>
              <span class="close"><a-icon class="icon-close11" type="close-circle" @click.stop="deleteSecondIt(item.id)"/></span>
            </div>
          </draggable>
        </div>

        <div style="display: flex">
          <a-input
              v-model.trim="secondText" :maxLength="4" addon-after="最多4个字" @pressEnter="pressEnter"
              placeholder="请输入二级选项卡名称">
          </a-input>
          <a-button type="primary" style="width: 100px;margin-left: 15px;" @click="pressEnter">
            确定
          </a-button>
        </div>

        <template v-for="component in current_second_list" >
          <div style="margin-top: 10px" v-if="component.active">
            <div class="title-box">
              <span style="flex: 0 0 100px;align-self: center">模块设置：</span>
            </div>
            <a-button type="primary" style="width: 150px;" @click="setCurrentSecondComponent(component)">
              添加二级选项卡模块
            </a-button>

            <draggable
                tag="div" class="tab-box"
                :list="component.components"
                v-bind="dragOptions">

              <div class="tab-item" :class="[component_tab_active == item.id?'active':'']" v-for="item in component.components" :key="item.id"
                   @click="chooseIt(component.components,item)">
                <span>{{item.id}}{{item.component}}</span><span class="close">
          <a-icon class="icon-close11" type="close-circle" @click.stop="deleteIt(component.components,item.id)"/></span>
              </div>
            </draggable>

            <div  v-if="current_tab.id" class="design-form-body" style="width: 370px;margin-top: -20px;">
              <!--<div class="title-box" style="margin-top: 15px;">-->
                <!--<span style="flex: 0 0 100px">选项模块</span><span style="flex: 1;">{{current_tab.component}}</span>-->
              <!--</div>-->
              <div>
                <!-- 数据配置界面 -->
                <template-config-detail
                    :layout="current_tab.layout"
                    :configs="current_tab.datas"
                    :rootConfig="current_tab.datas"
                    type="datas"
                    key="datas">
                </template-config-detail>
              </div>
            </div>

          </div>
        </template>

      </div>
      <template slot="footer">
        <a-button key="submit" type="primary"  @click="handleSecondOk">
          确定
        </a-button>
      </template>
    </a-modal>

    <a-modal v-model="visible" title="选择组件" @ok="handleOk">
      <a-radio-group v-model="choose_type">
        <a-radio :style="radioStyle" :value="'2'">
          商品组
        </a-radio>
        <a-radio :style="radioStyle" :value="'6'">
          单图
        </a-radio>
      </a-radio-group>
    </a-modal>
  </div>
</template>

<script>
	import draggable from 'vuedraggable';
	import imageUpload from '../../../../system-components/image-upload/index.vue';
	import imagesUpload from '../../../../system-components/images-upload/index.vue'
	// 配置项编译器
	// import templateConfigDetail from '../template-config-detail.vue';

	export default {
		components: {
			draggable,
			imageUpload,
			imagesUpload
			// templateConfigDetail
		},

		props: ['value', 'config', 'rootConfig'],

		data() {
			return {
				// tab_list: [],  //选项卡列表
				visible: false, //显示选择组件弹窗
				choose_type: '', //当前选择的组件
				tab_active: '', //当前选择的二级选项卡
				component_tab_active: "", //当前选择的二级选项卡的组件
				showSecondTab: false, //显示二级选项卡弹窗

				secondText: '',  //二级选项卡的输入框
				second_current_id: '', //当前弹窗设置的二级选项卡ID
				current_second_list: [], //当前弹窗设置的二级选项卡的组件数组
				current_tab: {}, //当前设置的二级选项卡组件数据
				current_second_component: [], //选择添加的二级选项卡的组件components

				current_ids_first: [], //一级选项卡现在已经添加过的id
				current_ids: [], //二级选项卡现在已经添加过的id
				current_ids_component: [], //二级选项卡组件模块现在已经添加过的id

        // 样式设置
				radioStyle: {
					display: 'block',
					height: '30px',
					lineHeight: '30px',
				},
				// 拖拽组件参数
				dragOptions: {
					animation: 200, // 动画时间
					group: "description",
					disabled: false,
					ghostClass: "sortable-ghost",
					dragClass: "sortable-drag",
					filter: ".ignore-elements"
				},
				loading: false,
				inDrag: false, // 是否正在拖拽
				inHover: 0, // 鼠标 hover 的 <li> 的 component_id
			}
		},

		computed: {
			tab_list: {
				get() {
					this.current_ids_first = [];
					if(this.value.length > 0) {
						this.value.map((item)=>{
							this.current_ids_first.push(item.id);
							item.second_list.map(list=> {
								list.components.map(component=> {
									component.remote_data = this.handle_data(component.datas)
                })
              })
						});
					}
					return this.value;
				},
				set(newValue) {
					this.$emit('input', newValue);
				}
			},
			component_list() {
				return this.$store.state.design.component_list.componentList || []
      }
		},
    mounted() {},
		methods: {
			// 一级选项卡操作
			/**
			 * 结束拖拽
			 */
			handleDragEnd (c) {
				this.inDrag = false;
			},
			openUpload(id) {
				this.$refs[`imageUpload${id}`][0].show();
			},
			sureImg(item,name,uploadShow,fileList) {
				    item.image = fileList[0].url;
			},
			deleteImg(item) {
				item.image = "";
			},
			/**
			 * 添加组件
			 */
			toAdd() {
				let current_value = this.tab_list;
				current_value.map((item)=>{
					this.current_ids_first.push(item.id);
				});
				let id = current_value.length + 1;
				while (this.current_ids_first.includes(id)) {
					id += 1;
				}
				this.current_ids_first.push(id);
				current_value.push({
					id: id,
					image: '',
					text: '',
					second_list: []
				});
				this.tab_list = current_value;
				this.$emit('input', this.tab_list);
			},
			/**
			 * 删除组件
			 * @param {Number} id 数组索引
			 */
			handle_component_delete (id) {
				let current_value = this.tab_list;
				for(let i=0;i<current_value.length;i++) {
					if(current_value[i].id == id) {
						current_value.splice(i, 1);
					}
				}
				this.tab_list = current_value;
				this.$emit('input', this.tab_list);
			},

			// 二级选项卡操作
      setCurrentSecondList(item) {
				// 设置当前的二级选项卡ID
				this.second_current_id = item.id;
				this.current_second_list = item.second_list;
	      this.current_second_list.map(lis=> {
		      lis.active = false;
	      });
				if(this.current_second_list[0]) {
					this.current_second_list[0].active = true;
					this.tab_active = this.current_second_list[0].id;

					if(this.current_second_list[0].components[0]) {
						this.current_tab = this.current_second_list[0].components[0];
						this.component_tab_active = this.current_tab.id;
					}else {
						this.current_tab = {};
						this.component_tab_active = "";
					}
				}
				this.showSecondTab = true;
      },
      handleSecondOk() {
      	// 找到对应的ID项替换数据
	      this.tab_list.reverse().reverse();
	      this.showSecondTab = false;
      },
			pressEnter() {
      	if(!this.secondText) {
      		return;
        }
				let current_value = this.current_second_list;
				current_value.map((item)=>{
					this.current_ids.push(item.id);
				});
				let id = current_value.length + 1;
				while (this.current_ids.includes(id)) {
					id += 1;
				}
				this.current_ids.push(id);
				let item = {
					id: id,
					active: true,
					title: this.secondText,
					components: [] //二级选项卡的模块数组
				};

				for (let i = 0; i < this.current_second_list.length; i++) {
					this.current_second_list[i].active = false;
				}
				this.current_second_list.push(item);
				this.tab_active = id;
				this.secondText = "";
				this.current_tab = {};
				this.component_tab_active = "";
			},
			chooseSecondIt(item) {
				for (let i = 0; i < this.current_second_list.length; i++) {
					if(this.current_second_list[i].id == item.id) {
						this.current_second_list[i].active = true;
					}else {
						this.current_second_list[i].active = false;
					}
				}
				this.tab_active = item.id;
				if(item.components[0]) {
					this.current_tab = item.components[0];
					this.component_tab_active = item.components[0].id
        }else {
					this.current_tab = {};
					this.component_tab_active = "";
        }
			},
			deleteSecondIt(id) {
				for (let i = 0; i < this.current_second_list.length; i++) {
					if (this.current_second_list[i].id == id) {
						this.current_second_list.splice(i, 1);
					}
				}
			},

			// 二级选项卡模块components操作
			chooseIt(components,item) {
				components.map(component=> {
					component.active = false;
					if(component.id == item.id) {
						component.active = true;
					}
				});
				this.current_tab = item;
				this.component_tab_active = item.id;
			},
			deleteIt(components,id) {
				components.map((item,i)=> {
					if(item.id == id) {
						components.splice(i, 1);
					}
        });
				if (this.current_tab.id == id) {
					this.current_tab = {};
					this.component_tab_active = "";
					if (components.length >= 1) {
						components[0].active = true;
						this.current_tab = components[0];
						this.component_tab_active = this.current_tab.id;
					}
				}
			},
			setCurrentSecondComponent(component) {
				// 设置选择的二级选项卡
        this.current_second_component = component.components;
				this.visible = true;
      },
			handleOk(e) {
				let current_value = this.current_second_component;
				current_value.map((item)=>{
					this.current_ids_component.push(item.id);
				});
				let id = current_value.length + 1;
				while (this.current_ids_component.includes(id)) {
					id += 1;
				}
				this.current_ids_component.push(id);
				let component = '';
				let datas = {};
				let layout = [];
				let uikey = '';
				switch (this.choose_type) {
					case '2':
						uikey = 'U_goods';
						component = '商品组';
						layout = [
							{
								title: '样式设置',
								groups: [
									'preview_color',
									'sort_style',
									'padding_top',
									'padding_bottom',
									'padding_left',
									'padding_right',
									'item_radius',
									'show_shadow',
									'show_border',
									'border_color',
									'good_tag',
									'button_type',
									'button_title',
									'button_bg_color',
									'button_color',
									'content_list',
                  'show_price_text',
									'disable_good',
								]
							},
							{
								title: '商品设置',
								groups: [
									// 'get_number',
									'list'
								]
							},
						];
						datas = {
							preview_color: {
								title: '背景颜色',
								type: 'color',
								value: "#F1F1F1",
							},
							sort_style: {
								title: "商品排列样式",
								type: "iconbox",
								value: {
									choose_icon: '2',
								},
								choose: 'single',
								isIcon: true,
								options: [
									{icon: 'icon-ht_goods_twopic', value: '2'},
									{icon: 'icon-ht_goods_vertical', value: '3'},
									{icon: 'icon-ht_goods_three', value: '4'},
									{icon: 'icon-ht_goods_threepic', value: '6'}
								]
							},
							padding_top: { title: '上边距', type: 'number', value: 0, col: 4, },
							padding_bottom: { title: '下边距', type: 'number', value: 0, col: 4, },
							padding_left: { title: '左边距', type: 'number', value: 0, col: 4, },
							padding_right: { title: '右边距', type: 'number', value: 0, col: 4, },
							item_radius: {
								title: '商品圆角',
								type: 'bar',
								value: 5,
								min: 0,
								max: 50
							},
							show_shadow: {
								title: '投影',
								type: 'switch',
								tips: '只在大图和横排排列样式下实现',
								value: false
							},
							show_border: {
								title: '显示边框',
								type: 'switch',
								tips: '只在大图和横排排列样式下实现',
								value: false
							},
							border_color: {
								title: '边框颜色',
								type: 'color',
								value: '#BFB7B7',
							},
							good_tag: {
								title: '商品属性',
								type: "iconbox",
								tips: '商品属性统一在左上角显示',
								value: {
									choose_icon: '0',
									image: '',
								},
								choose: 'single',
								isIcon: false,
								options: [
									{label: '无', value: '0'},
									{label: '推荐', value: '1'},
									{label: '热销', value: '2'},
									{label: '新上', value: '3'},
									{label: '包邮', value: '4'},
									{label: '限时', value: '5'},
									{label: '自定义', value: '7'}
								]
							},
							button_type: {
								title: '购买按钮样式',
								tips: '选择一排三个商品的排列方式时无法选择样式一或者样式二',
								type: 'radio',
								value: '4',
								options: [
									{label: '无', value: '0'},
									{label: '样式一', value: '1'},
									{label: '样式二', value: '2'},
									{label: '样式三', value: '3'},
									{label: '样式四', value: '4'},
									{label: '样式五', value: '5'},
									{label: '样式六', value: '6'},
								]
							},
							button_title: {
								title: '购买按钮文字',
								tips: '按钮文字只在选择有文字的样式时生效',
								type: 'text',
								value: '立即购买'
							},
							button_bg_color: {
								title: '购买按钮背景颜色',
								type: 'color',
								value: '#ff2c29',
							},
							button_color: {
								title: '购买按钮颜色',
								type: 'color',
								value: '#ffffff',
							},
							content_list: {
								title: "内容显示",
								tips: '爱心值和赠送积分只能选一个显示，同时选择时优先显示爱心值',
								type: "checkbox",
								value: ['1','2','3','7'],
								options: [
									{label: "标题", value: "1"},
									{label: "原价", value: "2"},
									{label: "现价", value: "3"},
									{label: "会员价", value: "4"},
									{label: "爱心值", value: "5"},
									{label: "赠送积分", value: "6"},
									{label: "销量", value: "7"},
									{label: "券后价", value: "8"},
								]
							},
							show_price_text: {
								title: '显示价格文字',
								type: 'switch',
								tips: '只控制券后价，原价，现价的文字',
								value: false
							},
							disable_good: {
								title: '失效产品',
								type: 'radio',
								value: '0',
								options: [
									{label: '不显示', value: '0'},
									{label: '样式一', value: '1'},
									{label: '样式二', value: '2'},
								]
							},
							// get_number: {
							// 	title: "商品显示数量",
							// 	type: 'number',
							// 	value: 1,
							// 	min: 1,
							// 	max: 100
							// },
							list: {
								title: '商品数据',
								tips: '除了单个选择商品可显示商品数据以外 其余都将使用默认商品数据占位，需要查看效果可保存后在移动端预览',
								value: [],
								chooseList: {
									list: [],
									tag: [],
									category: [],
									supplier: [],
									store: [],
									hotel: [],
								},
								chooseType: [
									{label: '单个选择', value: 'list'},
									{label: '选择标签', value: 'tag'},
									{label: '选择分类', value: 'category'},
									{label: '供应商', value: 'supplier'},
									{label: '门店', value: 'store'},
									{label: '酒店', value: 'hotel'}
								],
								type: 'goodList',
								choose: 'good'
							},
							goods_type: {
								title: '选择类型',
								type: 'radio',
								value: 'list',
								options: []
							}
						};
						break;
					case '6':
						uikey = 'U_simplegraph';
						component = '单图';
						layout = [
							{
								title: '单图组件设置',
								groups: [
									'padding_top',
									'padding_bottom',
									'padding_left',
									'padding_right',
									'picture_border',
									'list'
								]
							}
						];
						datas = {
							padding_top: { title: '上边距', type: 'number', value: 0, col: 4, },
							padding_bottom: { title: '下边距', type: 'number', value: 0, col: 4, },
							padding_left: { title: '左边距', type: 'number', value: 0, col: 4, },
							padding_right: { title: '右边距', type: 'number', value: 0, col: 4, },
							picture_border: {title: '图片圆角', type: 'bar', value: 0, min: 0, max: 100},
							list: {
								title: "添加单图",
								type: "list",
								notShowText: true,
								// notShow: true,
								hotArea: true,
								choose_title: {
									choose_option: [
										{label: "普通样式", value: "2"},
										{label: "绘制热区", value: "3"},
									]
								},
								value: []
							},
							choose_style: {
								title: '选择方式',
								type: 'radio',
								value: '2',
								options: []
							},
						};
						break;
					default:
						component = '无';
						uikey = 'U_goods';
						return;
				}
				let item = {id: id, type_id: this.choose_type, uikey: uikey, component: component, datas: datas, layout: layout, name: '', active: true};

				for (let i = 0; i < this.current_second_component.length; i++) {
          this.current_second_component[i].active = false;
				}
				this.current_second_component.push(item);
				this.current_tab = item;
				this.component_tab_active = item.id;

				this.visible = false;
			},
			/**
			 * 处理数据
			 * @param {String} datas
			 * **/
			handle_data(datas) {
				let handleDatas = {};
				if(datas) {
					Object.keys(datas).map(key => {
						handleDatas[key] = datas[key].value;
					});
				}
				return handleDatas;
			},
		}
	}
</script>
<style lang="less" scoped>
  .tab-box {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
  }

  .tab-item {
    cursor: move;
    border: 1px solid #333333;
    color: #333333;
    padding: 5px 10px;
    margin: 5px;
    .close {
      cursor: pointer;
      padding: 2px 5px;
      margin-left: 5px;
    }
    &.active {
      border: 0;
      background-color: rgba(41, 186, 156, 0.15);
      color: #29ba9c;
    }
  }

  .title-box {
    display: flex;
    margin-bottom: 10px;
  }

  // 拖拽区域
  .sortable-body {

    // 删除所有组件
    .button-clear-all {
      display: inline-block;
      width: 88px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      margin-bottom: 12px;
      font-size: 14px;
      font-weight: bold;
      cursor: pointer;
      &:hover {
        background: #29ba9c;
        color: #ffffff;
        border-radius:12px;
      }
    }

    // 组件列表
    ul {
      list-style: none;
      padding: 0px;
      margin: 0px;

      li {
        cursor: move;
        position: relative;
        padding: 25px 10px;
        margin-bottom: 16px;
        width: 100%;
        /*height: 48px;*/
        /*line-height: 48px;*/
        background: #fff;
        box-sizing: border-box;
        box-shadow: 0px 0px 0px 1px #E9EAEC;
        display: flex;
        flex-direction: column;


        // 鼠标滑过
        &.in-hover {
          /*background: #29ba9c;*/
          /*color: #fff;*/
          box-shadow: 0px 2px 6px 0px rgba(188,195,206,0.8);
          .buttons {
            color: #29ba9c;
            display: block;
          }
        }

        // 拖拽中
        &.sortable-ghost, &.sortable-chosen {
          /*opacity: .2 !important;*/
          /*background: #29ba9c;*/
          box-shadow: 0px 2px 6px 0px rgba(188,195,206,0.8);
          /*color: #fff;*/
          span {
            color: #29ba9c;
          }
        }

        p {
          margin: 0px;
        }

        .bottom {
          display: flex;
          margin-top: 10px;
        }

        .id-name {
          position: absolute;
          left: 10px;
          top: 0px;
        }

        // 按钮区域
        .buttons {
          display: none;
          position: absolute;
          right: 10px;
          top: 0px;
          text-align: right;

          > span {
            text-align: center;
            vertical-align: middle;
            display: inline-block;
            background: #fff;
            border-radius: 100%;
            width: 24px;
            height: 24px;
            line-height: 24px;
            &:hover {
              cursor: pointer;
            }
          }
        }
      }
    }
  }

  .flip-list-move {
    transition: transform 0.5s;
  }
  .no-move {
    transition: transform 0s;
  }

  .choose-img {
    margin: 0 auto;
    width: 65px;
    height: 65px;
    border-radius: 3px;
    border: dashed 1px #e2e2e2;
    display: flex;
    flex-direction: column;
    align-self: center;
    justify-content: center;
    text-align: center;
    color: #5e5e5e;
    cursor: pointer;
    font-size: 12px;
    i {
      height: 28px;
    }
  }
  .choose-img:hover, .show-img:hover {
    color: #29ba9c;
    border-color: #29ba9c;
  }

  .show-img {
    position: relative;
    width: 65px;
    margin: 0 auto;
    border: dashed 1px #e2e2e2;
    cursor: pointer;
    img {
      width: 100%;
    }
    .icon-close11 {
      position: absolute;
      top: -10px;
      right: -9px;
      color: #999;
      font-size: 18px;
    }
  }

  .tips {
    margin-top: 15px;
    color: #b4b4b4;
  }
</style>
